package com.zzl.alligator.management.system.controller;

import cn.hutool.core.map.MapUtil;
import com.zzl.alligator.common.enums.BusinessTypeEnum;
import com.zzl.alligator.common.util.ExcelUtils;
import com.zzl.alligator.common.util.ServletUtils;
import com.zzl.alligator.framework.aspectj.annotation.Log;
import com.zzl.alligator.framework.base.controller.BaseController;
import com.zzl.alligator.framework.security.LoginUser;
import com.zzl.alligator.framework.security.service.TokenService;
import com.zzl.alligator.framework.support.web.vo.JsonResult;
import com.zzl.alligator.management.system.domain.SysPost;
import com.zzl.alligator.management.system.domain.SysRole;
import com.zzl.alligator.management.system.domain.SysUser;
import com.zzl.alligator.management.system.service.ISysPostService;
import com.zzl.alligator.management.system.service.ISysRoleService;
import com.zzl.alligator.management.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * 用户controller
 *
 * @author zhouziliang
 * @since 2020/6/26
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;
    /**
     * 根据条件查找用户列表
     *
     * @param user 查询条件
     * @return 结果
     */
    @GetMapping
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    public JsonResult userList(SysUser user) {
        startPage();
        List<SysUser> list = userService.findUserList(user);
        return JsonResult.success(getDataTable(list));
    }

    /**
     * 根据用户Id查找用户信息
     *
     * @param userId 用户ID
     * @return 用户
     */
    @GetMapping("/{userId}")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    public JsonResult findUserById(@Validated @PathVariable Long userId) {
        SysUser user = userService.findUserById(userId);
        List<SysRole> allRole = roleService.findAllRole();
        List<SysPost> allPost = postService.fndAllPost();
        List<Long> roleIds = roleService.findRoleListByUserId(userId);
        List<Long> postIds = postService.findPostListByUserId(userId);

        Map<Object, Object> map = MapUtil.builder()
                .put("user", user)
                .put("roles", allRole)
                .put("posts", allPost)
                .put("roleIds", roleIds)
                .put("postIds", postIds)
                .build();

        return JsonResult.success(map);
    }

    /**
     * 新增用户
     *
     * @param user 用户信息
     * @return 结果
     */
    @PostMapping
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(businessType = BusinessTypeEnum.INSERT, isSaveRequestData = true,
            title = "用户信息")
    public JsonResult addUser(@Validated @RequestBody SysUser user) {
        return JsonResult.success(userService.insertUser(user));
    }

    /**
     * 更新用户
     *
     * @param user 用户
     * @return 结果
     */
    @PutMapping
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(businessType = BusinessTypeEnum.UPDATE, isSaveRequestData = true,
            title = "用户信息")
    public JsonResult updateUser(@RequestBody SysUser user) {
        return JsonResult.success(userService.updateUser(user));
    }

    /**
     * 获取角色和岗位全量列表
     *
     * @return 角色和岗位全量列表
     */
    @GetMapping("/rolePost")
    public JsonResult rolePost() {
        List<SysRole> allRole = roleService.findAllRole();
        List<SysPost> allPost = postService.fndAllPost();
        Map<Object, Object> map = MapUtil.builder()
                .put("roles", allRole)
                .put("posts", allPost)
                .build();
        return JsonResult.success(map);
    }


    /**
     * 更新用户
     *
     * @param user 用户
     * @return 结果
     */
    @PutMapping("/changeStatus")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    public JsonResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        return JsonResult.success(userService.changeUserStatus(user));
    }


    /**
     * 删除用户
     *
     * @param userId 用户Id
     * @return 删除结果
     */
    @DeleteMapping("/{userId}")
    @PreAuthorize("@ss.hasPermi('system:user:delete')")
    @Log(businessType = BusinessTypeEnum.DELETE, title = "删除用户信息")
    public JsonResult deleteUserById(@PathVariable Long userId) {
        return JsonResult.success(userService.deleteUserById(userId));
    }

    /**
     * 导出数据
     * @param sysUser 查询条件
     * @return 结果
     */
    @GetMapping("/export")
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @Log(businessType = BusinessTypeEnum.EXPORT, title = "导出用户列表")
    public JsonResult exportExcel(SysUser sysUser) {
        List<SysUser> list = userService.findUserList(sysUser);
        ExcelUtils<SysUser> util = new ExcelUtils<>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    /**
     * 导入用户信息
     *
     * @return 结果
     */
    @GetMapping("/importTemplate")
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    public JsonResult importTemplate() {
        ExcelUtils<SysUser> util = new ExcelUtils<>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 通过 excel 导入数据
     *
     * @return 结果
     */
    @PostMapping("importData")
    @Log(title = "导入用户信息", businessType = BusinessTypeEnum.IMPORT)
    public JsonResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtils<SysUser> utils = new ExcelUtils<>(SysUser.class);
        List<SysUser> userList = utils.importExcel(file.getInputStream());

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return JsonResult.success(message);
    }

}
